/**
 * HttpSend
 *
 * @author 冰凝
 * @date 2022/12/11 12:29
 */
export function HttpSend(request: HttpRequest): Promise<void> {

    return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest()

        xhr.open(request.method, request.url, true)
        xhr.send(request.body)

        xhr.onreadystatechange = () => {
            if (xhr.readyState === XhrReadyState.COMPLETED) {
                if (xhr.status >= 200 && xhr.status <= 299) {
                    resolve(xhr.response)
                } else {
                    reject(xhr.response)
                }
            }
        }
    })
}

export interface HttpRequest<
    Q = Record<string, any>,
    H = Record<string, any>,
    B = any
> {
    /**
     * HTTP 请求URL
     */
    url: string | URL
    /**
     * HTTP 请求方法
     */
    method: 'GET' | 'PUT' | 'POST' | 'DELETE'
    /**
     * URL query 参数
     */
    query?: Q
    /**
     * HTTP 请求头
     */
    header?: H
    /**
     * 请求体
     */
    body?: B
}

enum XhrReadyState {
    /**
     * 未初始化
     */
    NOT_INIT = 0,
    /**
     * 已连接
     */
    CONNECTED = 1,
    /**
     * 已接收
     */
    RECEIVED = 2,
    /**
     * 处理中
     */
    PROCESSING = 3,
    /**
     * 已完成
     */
    COMPLETED = 4
}
